from ...lib_pos_frame import Lib_pos_Frame
import tkinter as tk
from tkinter import messagebox
import time
from src.hardware.zlgcan.zlgcan import *
import json
from src.globals import g_ic_debugger

from src.types_pydantic.config_types import Functest_PosUnit_Data_Type
from src.types_pydantic.zlgcan_zuds_types import Uds_Request_Type
from src.test_lib.functest_Can_Can import FunctestTemplate_Can_Can


class Can_Can_Lib_Frame(Lib_pos_Frame):
    def __init__(self, master, rooter, config_file, pos_Type=None, pos_Toplevel_UI=None):
        super().__init__(master=master, rooter=rooter, config_file=config_file,
                         pos_data_Type=pos_Type, pos_Toplevel_UI=pos_Toplevel_UI)

        self.ROOTER = rooter
        self.ROOTER.can_can_lib_frame = self
        if pos_Type is None:
            self.pos_data_Type = Functest_PosUnit_Data_Type
        if pos_Toplevel_UI is None:
            self.pos_Toplevel_UI = FunctestTemplate_Can_Can

        # 加载配置文件
        self.load_lib_config()
        self.create_posBtns()
        # 更新特殊按钮函数
        self.unitTab_btn_function_update()

    def load_lib_config(self):
        with open(self.config_file, 'r', encoding='utf-8') as f:
            self.lib_config = json.load(f)
        self.pos_data_configs = self.lib_config['func_tests']

    def create_posBtns(self):
        for pos, item in self.pos_data_configs.items():
            self.LIB_UNIT_DATA_DICT[pos] = self.pos_data_Type(**item)
            # g_ic_debugger(self.LIB_UNIT_DATA_DICT[pos])

            def btn_click(pos):
                return lambda: self.pos_Toplevel_UI(
                    self, self.ROOTER, self.LIB_UNIT_DATA_DICT[pos])
            # 通过函数执行每次得到一个闭包，这样就可以在每次点击时，得到不同的pos
            # 否则，所有的按钮都会指向最后一个pos
            self.LIB_UNIT_FUN_DICT[pos] = btn_click(pos)

            self.LIB_UNIT_BTN_DICT[pos].config(
                text=item['name'], background='orange', command=self.LIB_UNIT_FUN_DICT[pos])
